#include <QFileInfo>
#include <QDebug>

#include "pageimagesparser.h"
#include "../utils.h"

namespace Jcr
{

class PageImagesParserPrivate
{
public:
    QList<QUrl> images;
};

static const QStringList ImageExtensions = QStringList() << "jpg" << "png" << "gif";
static inline bool isImageFile(const char* file)
{
    QString strFile(file);
    return ImageExtensions.contains(strFile.mid(strFile.length() - 3));
}

PageImagesParser::PageImagesParser(QObject* parent) : AbstractPageParser(parent)
{
    d_ptr = new PageImagesParserPrivate;
}

PageImagesParser::~PageImagesParser()
{
    delete d_ptr;
}

void PageImagesParser::processNode(GumboNode *node)
{
    if (node->type != GUMBO_NODE_ELEMENT)
        return;

    GumboAttribute* hrefAttr = gumbo_get_attribute(&node->v.element.attributes, "href");
    if (hrefAttr) {
        if (isImageFile(hrefAttr->value)) {
            QUrl imageUrl = QUrl(QString(hrefAttr->value));
            if (!d_ptr->images.contains(imageUrl))
                d_ptr->images.append(imageUrl);
        }
    }

    GumboAttribute* srcAttr = gumbo_get_attribute(&node->v.element.attributes, "src");
    if (srcAttr) {
        if (isImageFile(srcAttr->value)) {
            QUrl imageUrl = QUrl(QString(srcAttr->value));
            if (!d_ptr->images.contains(imageUrl))
                d_ptr->images.append(imageUrl);
        }
    }

    GumboVector* children = &node->v.element.children;
    int childCount = children->length;
    for (int i = 0; i < childCount; i++) {
        GumboNode* child = static_cast<GumboNode*>(children->data[i]);
        processNode(child);
    }
}

void PageImagesParser::finalize()
{
    emit finished();
}

const QList<QUrl>& PageImagesParser::images() const
{
    return d_ptr->images;
}

} // namespace jcr
